#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>

struct Tuple
{
  int num;
  char c;
} * tuple_list;

FILE *files[255];
size_t file_num = 0;

size_t run_length_encoding()
{
  size_t next_empty = 0;
  char current = 0;
  size_t result = 0;
  char previous = fgetc(files[0]);
  for (size_t current_file = 0; current_file < file_num; ++current_file)
  {
    if (current_file != 0)
    {
      struct Tuple *last_tuple = &(tuple_list[result - 1]);
      char first = 0;
      while ((first = fgetc(files[current_file])) == previous)
      {
        (last_tuple->num)++;
      }
    }
    size_t count = 0;

    do
    {
      if (current == EOF)
        break;
      current = fgetc(files[current_file]);
      if (current == previous)
      {
        count++;
      }
      else
      {
        count++;
        tuple_list[next_empty].c = previous;
        tuple_list[next_empty].num = count;
        result++;
        next_empty++;
        count = 0;
      }
      if (current != EOF)
        previous = current;
    } while ((current) != EOF);
  }
  return result;
}

int main(int argc, char *const argv[])
{
  if (argc <= 1)
  {
    fprintf(stdout, "seuzip: file1 [file2 ...]\n");
    exit(EXIT_FAILURE);
  }

  for (size_t i = 1; i < argc; ++i)
  {
    files[i - 1] = fopen(argv[i], "r");
    file_num++;
    if (files[i - 1] == NULL)
    {
      fprintf(stderr, "Can not read file %s\n", argv[i]);
      exit(EXIT_FAILURE);
    }
  }
  tuple_list = calloc(sizeof(struct Tuple), 1000000);

  size_t result = run_length_encoding();
  for (size_t j = 0; j < result; ++j)
  {
    fwrite(&(tuple_list[j]), 5, 1, stdout);
  }
  free(tuple_list);
}